import Ajv from 'ajv';
import { ApiTrack } from '..';
import { Rule, RuleGroupItem, Section, EventName } from '../types';

const ajv = new Ajv({
  allErrors: true,
});

const jsonSchemaCompile = (section?: Section) => {
  if (section) {
    for (const validatorUnit of Object.values(section)) {
      if (validatorUnit.json_schema) {
        validatorUnit.schema_compiled = ajv.compile(validatorUnit.json_schema);
      }
    }
  }
  return section;
};

export const ruleCompile = (rule: Rule | RuleGroupItem, apiTrack: ApiTrack): Rule | undefined => {
  const { api_path = '', preset_sences, condition, validator, info, ...other_info } = rule;
  try {
    const start = Date.now();
    const conditionCompiled = jsonSchemaCompile(condition);
    const validatorCompiled = jsonSchemaCompile(validator);
    apiTrack.reporter?.sendLog?.(EventName.RuleCompileSuccess, {
      categories: {
        api_path,
        ...info,
        ...other_info,
      },
      metrics: {
        compile_timing: Date.now() - start,
      },
    });
    return {
      api_path,
      info: {
        api_path,
        ...info,
        ...other_info,
      },
      preset_sences,
      condition: conditionCompiled,
      validator: validatorCompiled,
    };
  } catch (error) {
    apiTrack.reporter.sendLog?.(EventName.RuleCompileFail, {
      categories: {
        api_path,
        ...info,
        ...other_info,
        error: String((error as Error)?.message || error),
      },
    });
  }
};
